package com.example.springbootweb_comprehensiveexample.controller;

import com.example.springbootweb_comprehensiveexample.pojo.Result;
import com.example.springbootweb_comprehensiveexample.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {
    @Autowired
    private AliOSSUtils aliOSSUtils;

    //本地存储文件的方式
    /*@PostMapping("/upload")
    public Result upload(String username, Integer age, MultipartFile image) throws Exception {

        log.info("上传文件: {}, {}, {}", username, age, image);

        //获取原始文件名
        String originalFilename = image.getOriginalFilename();

        //构造唯一的文件名（不重复） -- uuid（通用唯一识别码）
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);//获取文件后缀
        String newFileName = UUID.randomUUID().toString() + extname; //构造新的文件名

        //将文件存在服务器磁盘目录：
        // T:\Java\JavaWeb\Back_end_development\WebPractice\UploadTest
        image.transferTo(new File("T:\\Java\\JavaWeb\\Back_end_development\\WebPractice\\UploadTest\\" + newFileName));

        return Result.success();

    }*/

    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {

        //调用阿里云oss工具类进行文件上传
        log.info("文件上传，文件名：{}", image.getOriginalFilename());
        String url = aliOSSUtils.upload(image);
        log.info("文件的url：{}", url);
        return Result.success(url);

    }

}
